// Copyright (c) 2019 Presto Labs Pte. Ltd.
// Author: xguo, gekim

#pragma once

#include <memory>
#include <string>

#include "coin2/base/string_util.h"
#include "coin2/exchange/base/symbology/currency.h"
#include "coin2/exchange/base/symbology/util.h"

namespace coin2::exchange::okex::symbology {

static const int64_t LUNA2_LIST_TIME =
    1653868800000000000L;  // TimestampFromDatetime(2020, 05, 30);

class OkexCurrency : public base::symbology::Currency,
                     public base::symbology::CurrencyFromStrMixin<OkexCurrency> {
 public:
  using ExchangeType = base::market::ExchangeType;
  using MarketType = base::market::MarketType;
  using Currency = base::symbology::Currency;
  using base::symbology::Currency::native_currency;

 public:
  explicit OkexCurrency(const std::string& currency)
      : Currency(currency, ToNativeCurrency(currency).value(), ExchangeType::Okex) {}

  static std::unique_ptr<OkexCurrency> FromNativeStrImpl(
      const std::string& native_currency_str,
      int64_t resolve_timestamp) {
    auto currency = FromNativeCurrency(native_currency_str, resolve_timestamp);
    if (currency) {
      return std::make_unique<OkexCurrency>(currency.value());
    }
    return {};
  }

  static std::unique_ptr<OkexCurrency> FromNormStrImpl(
      const std::string& currency_str,
      int64_t resolve_timestamp) {
    auto native_currency = ToNativeCurrency(currency_str);
    if (!native_currency) {
      return {};
    }
    auto norm_currency = FromNativeCurrency(*native_currency, resolve_timestamp);
    if (!norm_currency) {
      return {};
    }
    return std::make_unique<OkexCurrency>(norm_currency.value());
  }

 private:
  static std::optional<std::string> ToNativeCurrency(const std::string& currency_str) {
    std::string native_currency_str;
    if (currency_str == "BCHSV") {
      native_currency_str = "BSV";
    } else if (currency_str == "BCHABC" || currency_str == "BCHN") {
      native_currency_str = "BCH";
    } else if (currency_str == "LUNA2") {
      return "LUNA";
    } else if (currency_str == "NANO") {
      return "XNO";
    } else {
      native_currency_str = currency_str;
    }
    return native_currency_str;
  }

  static std::optional<std::string> FromNativeCurrency(
      const std::string& native_currency_str,
      int64_t resolve_timestamp) {
    const auto native_currency_str_upper = StringToUpperCopy(native_currency_str);
    if (native_currency_str_upper == "BSV") {
      return "BCHSV";
    } else if (native_currency_str_upper == "BCH") {
      if (resolve_timestamp >= base::symbology::BCHA_BCHN_FORK_TIME) {
        return "BCHN";
      } else {
        return "BCHABC";
      }
    } else if (native_currency_str_upper == "LUNA" && resolve_timestamp >= LUNA2_LIST_TIME) {
      return "LUNA2";
    } else if (native_currency_str_upper == "XNO") {
      return "NANO";
    } else {
      return native_currency_str_upper;
    }
  }
};

}  // namespace coin2::exchange::okex::symbology
